package kr.saeildamil.androidforstudy2.ch28;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;

import kr.saeildamil.androidforstudy2.R;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.ListView;

public class JsonParserActivity extends Activity {
	ListView list;
	ProgressDialog mProgress;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ch28_xmlparser);
		list = (ListView) findViewById(R.id.ch28_xmlparser_listview);

		new ParsingXml().execute("order.json");
	}

	private class ParsingXml extends AsyncTask<String, Void, ArrayList<Item>> {

		@Override
		protected void onPreExecute() {
			mProgress = ProgressDialog.show(JsonParserActivity.this, "Wait",
					"Now Making order.json");
		}

		@Override
		protected void onPostExecute(ArrayList<Item> result) {
			MyAdapter adapter = new MyAdapter(result, JsonParserActivity.this);
			mProgress.dismiss();
			list.setAdapter(adapter);
		}

		@Override
		protected ArrayList<Item> doInBackground(String... params) {
			StringBuilder sb = new StringBuilder();
			String str = null;
			try {
				BufferedReader br = new BufferedReader(new InputStreamReader(
						openFileInput(params[0])));
				while ((str = br.readLine()) != null) {
					sb.append(str);
				}
				br.close();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return parsingXml(sb.toString());
		}

		private ArrayList<Item> parsingXml(String xml) {
			ArrayList<Item> arItem = new ArrayList<Item>();
			Item itemClass;
			
			try {
				JSONArray json = new JSONArray(xml);
				for (int i = 0; i < json.length(); i++) {
					JSONObject order = json.getJSONObject(i);
					itemClass = new Item();
					itemClass.setItemName(order.getString("Product"));
					itemClass.setItemPrice(order.getInt("Price"));
					itemClass.setMakerName(order.getString("Maker"));
					arItem.add(itemClass);
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
			return arItem;
		}
	}
}
